<?php

namespace App\Http\Utils\Integral;

use Illuminate\Support\Facades\DB;

/**
 * Class Shop
 * @package App\Http\Utils\Integral
 */
class Shop
{
    /**
     * @var string
     */
    public $shopId;

    /**
     * @var float
     */
    public $totalAmount = 0;

    /**
     * @var array
     */
    protected $flows = [];

    /**
     * @var bool
     */
    public $day_enabled = false;

    /**
     * @var bool
     */
    public $mal_enabled = false;

    /**
     * @var bool
     */
    public $luck_enabled = false;

    /**
     * Shop constructor.
     * @param string $shopId 商户ID
     */
    public function __construct($shopId)
    {
        $this->shopId = $shopId;
        $this->earnings();
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return (string)$this->shopId;
    }

    /**
     *
     */
    private function earnings()
    {
        $shop = DB::table('shop')
            ->where([
                'shop_id' => $this->shopId
            ])->lockForUpdate()
            ->first();
        if (is_null($shop)) {
            DB::table('shop')->insert([
                'shop_id'      => $this->shopId,
                'total_amount' => 0,
                'day_enabled'  => 'true',
                'mal_enabled'  => 'true',
                'luck_enabled' => 'true',
                'create_time'  => Time::current(),
                'update_time'  => Time::current(),
            ]);
        } else {
            $this->totalAmount = $shop->total_amount;
            $this->day_enabled = ($shop->day_enabled === 'true');
            $this->mal_enabled = ($shop->mal_enabled === 'true');
            $this->luck_enabled = ($shop->luck_enabled === 'true');
        }
    }

    /**
     * @param string $orderNum 订单号
     * @param string $userId 用户ID
     * @param float $integral 积分
     * @param string $roleName 规则名
     * @param float $taskId 任务名
     */
    public function flow($orderNum, $userId, $integral, $roleName, $taskId)
    {
        $this->flows[] = [
            'shop_id'     => $this->shopId,
            'user_id'     => $userId,
            'order_num'   => $orderNum,
            'integral'    => $integral,
            'role_name'   => $roleName,
            'history'     => $this->totalAmount + $integral,
            'task_id'     => $taskId,
            'create_time' => Time::current(),
            'update_time' => Time::current(),
        ];
        $this->totalAmount = $this->totalAmount + $integral;
    }

    /**
     *
     */
    public function record()
    {
        DB::table('shop')
            ->where([
                'shop_id' => $this->shopId,
            ])->update([
                'total_amount' => $this->totalAmount,
                'update_time'  => Time::current(),
            ]);
        if (!empty($this->flows)) {
            DB::table('shop_flow')->insert($this->flows);
        }
    }
}